//
//  TF_inviteView.m
//  个人资料
//
//  Created by 莫瑞权 on 2022/12/12.
//  Copyright © 2022 ix. All rights reserved.
//
#define KIsiPhoneX  @available(iOS 11.0, *) && UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom > 0.0
#import "TF_inviteView.h"
#import "TF_inviteCell.h"
#import "TF_inviteModel.h"
#define DEVICEMODEL [UIDevice currentDevice].model
#define IsIPAD [DEVICEMODEL hasPrefix:@"iPad"]
@interface TF_inviteView ()<UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout>


@property(nonatomic,strong)UIViewController*ViewController;
@property(nonatomic,strong)UICollectionView *collectionView;//常用语collectionView
@property(nonatomic,strong)UILabel *pictureSavel;
@property(nonatomic,strong)UIImageView *showImage;

@property(nonatomic,strong)NSMutableArray *list;
@property(nonatomic,assign)BOOL saved;
//导航栏
@property(nonatomic,strong)UIView *navigationBarView;
@property(nonatomic,strong)UIButton *closureBtn;
@property(nonatomic,strong)UIButton *XBtn;
@property(nonatomic,assign)bool tf_navigationBarHidden;
//@property(nonatomic,assign)bool tf_statusBarHidden;
@property(nonatomic,strong)UILabel *titleLabel;
@end
@implementation TF_inviteView

#pragma mark - 保存至相册
- (void)longPress:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        
        UIImageWriteToSavedPhotosAlbum(skinView.UIGraphicsBeginImageContextWithOptions, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        
    
    }
}
//指定回调方法
- (void)image: (UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
   
    if(error != NULL){
        [self immediate:@"保存图片失败,请打开相册权限"];
    }else{
        self.saved = YES;
        [self immediate:@"保存图片成功"];
    }


    
    
}
- (void)immediate:(NSString*)title
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.saved = false;
    }];

    [alertController addAction:updateAction];
    if (IsIPAD) {
        alertController.popoverPresentationController.sourceView = self.ViewController.view;
        alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    }

    if (self.ViewController != nil) {
       [self.ViewController presentViewController:alertController animated:YES completion:nil];
    }
    
    
}

- (void)closureBtnClick
{

    self.ViewController.navigationController.navigationBar.hidden = self.tf_navigationBarHidden;
    self.hidden = true;
    

}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.hidden = true;
        
        self.navigationBarView = [[UIView alloc]init];
        self.navigationBarView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.navigationBarView];
        
        self.closureBtn = [[UIButton alloc]init];
        [self.navigationBarView addSubview:self.closureBtn];
        
        self.XBtn = [[UIButton alloc]init];
        [self.navigationBarView addSubview:self.XBtn];
        UIImage *newImage = [TF_inviteView getImage:@"关闭邀请卡"];
        [self.closureBtn setImage:newImage forState:UIControlStateNormal];
        [self.closureBtn addTarget:self action:@selector(closureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.XBtn addTarget:self action:@selector(closureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        //-----------------------
        
        self.titleLabel = [[UILabel alloc]init];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.numberOfLines = 0;
        [self.navigationBarView addSubview:self.titleLabel];

        NSMutableAttributedString *titleLabel_string = [[NSMutableAttributedString alloc] initWithString:@"邀请卡" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 17], NSForegroundColorAttributeName: [UIColor colorWithRed:20/255.0 green:23/255.0 blue:26/255.0 alpha:1.0]}];

        self.titleLabel.attributedText = titleLabel_string;
        self.titleLabel.textColor = [UIColor colorWithRed:20/255.0 green:23/255.0 blue:26/255.0 alpha:1.0];
        
        [self.navigationBarView addSubview:self.titleLabel];
        //-------------
        self.backgroundColor = [UIColor colorWithRed:8/255.0 green:27/255.0 blue:45/255.0 alpha:1.0];
        
        // 长按
           UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [self addGestureRecognizer:longPress];
        
        
        self.list = [[NSMutableArray alloc]init];
        
        
        for (int  i = 0; i< 6; i++) {
            TF_inviteModel *model = [[TF_inviteModel alloc]init];
            if (i==0) {
                model.isSelected = true;
            }
            [self.list addObject:model];
        }

        //------------
        
        self.showImage = [[UIImageView alloc]init];
        self.showImage.backgroundColor = [UIColor clearColor];
        [self addSubview:self.showImage];
        //----------
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

        layout.itemSize = CGSizeMake(50, 50);
        //平台
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        [self.collectionView registerClass:[TF_inviteCell class] forCellWithReuseIdentifier:@"TF_inviteCell"];
        [self addSubview:self.collectionView];
        //----------------------------
        self.pictureSavel = [[UILabel alloc] init];
        self.pictureSavel.backgroundColor =[UIColor colorWithRed:35/255.0 green:52/255.0 blue:68/255.0 alpha:1.0];;
        self.pictureSavel.numberOfLines = 0;
        [self addSubview:self.pictureSavel];
        self.pictureSavel.text = @"长按图片保存";
        self.pictureSavel.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
        self.pictureSavel.font = [UIFont systemFontOfSize:16];
        self.pictureSavel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}
 - (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat collectionViewH = 66.0;
    CGFloat collectionViewY = self.frame.size.height-collectionViewH;
    if(KIsiPhoneX)
    {
        collectionViewY = collectionViewY - 32;
    }
    self.collectionView.frame = CGRectMake(0, collectionViewY, self.frame.size.width, collectionViewH);
    self.collectionView.backgroundColor = [UIColor clearColor];
    //---------
    CGFloat pictureSavelH = 30;
    CGFloat pictureSavelY = collectionViewY-pictureSavelH;
    self.pictureSavel.frame = CGRectMake(0,pictureSavelY,self.frame.size.width,pictureSavelH);
    //-----------------------------------------
  
   
    CGFloat navigationBarViewY = 0;

    if(self.navigationBarView.isHidden == false && self.hidden == false)
    {

      
        float statusBarHeight = 44.0;
        //有状态栏
        if([UIApplication sharedApplication].statusBarHidden==false)
        {

            navigationBarViewY = [self vg_statusBarHeight];
           
            
            //有导航栏
            if(self.tf_navigationBarHidden==false)
            {
                /// 状态栏+导航栏的高度
                navigationBarViewY = [self vg_navigationFullHeight];

            }
        }

     

        self.navigationBarView.frame = CGRectMake(0, 0, self.frame.size.width,navigationBarViewY+statusBarHeight );
        
        self.titleLabel.frame = CGRectMake(0,navigationBarViewY+(statusBarHeight-24)/2,self.frame.size.width,24);
        
        
         self.XBtn.frame = CGRectMake(20-3, navigationBarViewY+(statusBarHeight-22)/2, 22, 22);
         
         self.closureBtn.frame = CGRectMake(20,navigationBarViewY+ (statusBarHeight-16)/2, 16, 16);
    }
    
    //-----------------
    CGFloat skinW = 375.0;
    CGFloat skinH = 667.0;
    CGFloat showImageY = 10;
    if(self.navigationBarView.isHidden == false && self.hidden == false)
    {
        showImageY = CGRectGetMaxY(self.navigationBarView.frame) + 10;
    }
    CGFloat showImageH = pictureSavelY-showImageY-10;
    CGFloat showImageW = skinW/skinH*showImageH;
    self.showImage.frame = CGRectMake((self.frame.size.width-showImageW)/2,showImageY, showImageW, showImageH);
}
#pragma mark 每组有多个个cell
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.list.count;
}

#pragma mark  每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TF_inviteCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TF_inviteCell" forIndexPath:indexPath];
    TF_inviteModel *model = self.list[indexPath.row];
    if(model.isSelected)
    {
        cell.SelectedImageView.hidden = false;
        cell.backgroundColorView.hidden = false;
    }else
    {
        cell.SelectedImageView.hidden = true;
        cell.backgroundColorView.hidden = true;
    }
    UIImage *newImage = [TF_inviteView getImage:[NSString stringWithFormat:@"skin_%li_thumbnail",indexPath.row+1]];
    cell.showImage.image = newImage;
    return cell;
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    CGFloat fSpacing = (self.frame.size.width-(50*6))/7;
    return UIEdgeInsetsMake(0, fSpacing, 0, fSpacing);//分别为上、左、下、右
}
// item 行间距(横) ==  cell 与左右间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//
//    CGFloat width = (self.frame.size.width-(50*6))/6;
//    return width;
//}
//item 列间距(纵)  上下间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    
//    CGFloat fSpacing =  8;
    CGFloat fSpacing = (self.frame.size.width-(50*6))/7;
    return fSpacing;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    self.showImage.image = [skinView currentViewScreenPhoto:indexPath.row+1];
    
    for (int  i = 0; i< self.list.count; i++) {
        TF_inviteModel *model = self.list[i];
        model.isSelected = false;
       
    }
    TF_inviteModel *model = self.list[indexPath.row];
    model.isSelected = true;
    [self.collectionView reloadData];
}
- (void)setCurrent:(skinModel*)model ViewController:(UIViewController*)ViewController
{
    self.tf_navigationBarHidden = ViewController.navigationController.navigationBar.hidden;
    
    
    ViewController.navigationController.navigationBar.hidden = true;
    //-------------
    
    
    self.hidden = false;
    
    if(model.isShowNavigationBar)
    {
        self.navigationBarView.hidden = false;
    }else
    {
        self.navigationBarView.hidden = true;
    }
    
    __weak typeof(self) weakSelf = self;
    self.ViewController = ViewController;
    
    for (int  i = 0; i< self.list.count; i++) {
        TF_inviteModel *new_model = self.list[i];
        new_model.isSelected = false;
       if(i == model.state-1)
       {
           new_model.isSelected = true;
       }
    }
    
    [skinView options:model.state];
    [skinView getCurrent:model callback:^( UIImage * _Nonnull image) {

        weakSelf.showImage.image = image;
        [weakSelf.collectionView reloadData];

    }];

    [self layoutSubviews];
}
/// 顶部状态栏高度（包括安全区）
- (CGFloat)vg_statusBarHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIStatusBarManager *statusBarManager = windowScene.statusBarManager;
        return statusBarManager.statusBarFrame.size.height;
    } else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}

/// 导航栏高度
- (CGFloat)vg_navigationBarHeight {
    return 44.0f;
}

/// 状态栏+导航栏的高度
- (CGFloat)vg_navigationFullHeight {
    return [self vg_statusBarHeight] + [self vg_navigationBarHeight];
}

+ (UIImage *)getImage:(NSString *)imageName {
    // 获取包含资源的 bundle，假设 TFInviteViewClass 是 Pod 中的一个类
    NSBundle *podBundle = [NSBundle bundleForClass:[TF_inviteView class]];
    NSURL *bundleURL = [podBundle URLForResource:@"TF_inviteView" withExtension:@"bundle"];
    NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL];
    
    if (resourceBundle) {
        NSString *imagePath = [resourceBundle pathForResource:imageName ofType:@"png"];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        
        if (image) {
            NSLog(@"Image loaded successfully");
            return image;
        } else {
            UIImage *newImage = [UIImage imageNamed:[NSString stringWithFormat:@"TF_inviteView.bundle/%@.png",imageName]];
            return newImage;
        }
    } else {
    
         UIImage *newImage = [UIImage imageNamed:[NSString stringWithFormat:@"TF_inviteView.bundle/%@.png",imageName]];
    
        return newImage;
    }
}
@end
